package com.jason.jasonapp.tools;

import java.util.Hashtable;

import com.jason.jasonapp.MainActivity;
import com.jason.jasonapp.R;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

public class JasonRadioPlayer extends Service implements OnCompletionListener, OnBufferingUpdateListener, OnPreparedListener, OnAudioFocusChangeListener {

	public static Hashtable<String,JasonRadioPlayerStation> stations = new Hashtable<String,JasonRadioPlayerStation>();
	static{
		stations.put("KBOS_TWR", new JasonRadioPlayerStation("Boston Tower", "http://d.liveatc.net/kbos_twr"));
		stations.put("KBOS_GND", new JasonRadioPlayerStation("Boston Ground", "http://d.liveatc.net/kbos_gnd"));
	}
	public static boolean serviceStarted = false;
	
	private MediaPlayer mp = null;
	private static String key = "KBOS_TWR";
	private String url = null;

	public void setKey(String key) {
		JasonRadioPlayer.key = key;
	}
	public String getKey() {
		return key;
	}
	
	public void stop() {
		if(mp != null) {
			if(mp.isPlaying()) {
				mp.stop();
			}
			mp.release();
			mp = null;
		}
	}
	public void play() {
		if(key != null)	{
			JasonRadioPlayerStation station = stations.get(key);
			if(station != null) {
				play(station.getURL(), station.getName());
			}
		}
	}
	public void play(String url, String stationName) {
		PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
		Notification notification = new NotificationCompat.Builder(getApplicationContext())
		.setContentTitle(getString(R.string.button_kbos))
		.setContentText(stationName)
		.setSmallIcon(R.drawable.ic_launcher)
		.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
		.setContentIntent(pi)
		.build();
		startForeground(1234, notification);
		
		AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
		if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
		    stopForeground(true);
		}
		else {
			this.url = url;
			play(url, audioManager);
		}
	}
	private void play(String url, AudioManager audioManager) {
		if(mp == null) {
			mp = new MediaPlayer();
		}
		else if(mp.isPlaying()) {
			mp.stop();
			mp.reset();
		}
		mp.setOnPreparedListener(this);
		mp.setOnCompletionListener(this);
		mp.setOnBufferingUpdateListener(this);
		mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
		try {
			mp.setDataSource(url);
			mp.prepareAsync();
		}catch(Exception e) {
			mp.release();
			mp = null;
			stopForeground(true);
			audioManager.abandonAudioFocus(this);
		}
	}
	public void playStop() {
		if(mp != null)	{
			if(mp.isPlaying()) {
				stop();
			}
			else {
				play();
			}
		}
		else {
			play();
		}
	}	
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onCreate() {
		serviceStarted = true;
		super.onCreate();
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		if(mp != null) {
			if(mp.isPlaying()) {
				mp.stop();
			}
			mp.release();
			mp = null;
		}
		serviceStarted = false;
	}
	@Override
	public void onCompletion(MediaPlayer arg0) {
		stopForeground(true);
		mp.release();
		mp = null;
	}
	@Override
	public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		String newKey = intent.getStringExtra("KEY");
		url = intent.getStringExtra("URL");
		if(newKey != null) {
			key = newKey;
		}
		if(url == null)	{
			play();
		}
		else {
			play(url, url);
		}
		super.onStartCommand(intent, flags, startId);
		return START_REDELIVER_INTENT;
	}
	@Override
	public void onPrepared(MediaPlayer mp) {
		mp.start();
	}
	@Override
	public void onAudioFocusChange(int focusChange) {
		switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
            if (mp == null){
            	play(url, (AudioManager)getSystemService(Context.AUDIO_SERVICE));
            }
            else if (!mp.isPlaying()) mp.start();
            mp.setVolume(1.0f, 1.0f);
            break;

        case AudioManager.AUDIOFOCUS_LOSS:
            stop();
            break;

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            if (mp.isPlaying()) mp.pause();
            break;

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            if (mp.isPlaying()) mp.setVolume(0.1f, 0.1f);
            break;
		}
	}
}
